package command

import (
	"errors"
	"strings"
	"time"

	"ssforward/common/dto"
	"ssforward/common/utils"
	"ssforward/internal/forward/models"
)

type ForwardRuleInsertReq struct {
	Name         string                 `json:"name"`
	ServerId     string                 `json:"serverId" vd:"len($)>0"`
	ProductModel string                 `json:"productModel"`
	DevSn        string                 `json:"devSn"`
	VariableMap  map[string]interface{} `json:"variableMap"`
	dto.UserInfo `search:"-"`
}

func (d *ForwardRuleInsertReq) Generate(model *models.SysForwardRule) error {
	model.Id = utils.SimpleUUID()
	model.Name = strings.TrimSpace(d.Name)
	model.ServerId = d.ServerId
	model.ProductModel = d.ProductModel
	model.DevSn = d.DevSn
	model.VariableMap = utils.MapToBytes(d.VariableMap)
	now := dto.LocalTime(time.Now())
	model.CreateTime = &now
	model.CreatorId = d.UserId
	model.AgencyId = d.AgencyId
	// 校验合法性
	if len(model.ProductModel) == 0 && len(model.DevSn) == 0 {
		return errors.New("需指定转发数据来源")
	}
	return nil
}

type ForwardRuleEditReq struct {
	Id           string                 `json:"id" vd:"len($)>0"`
	Name         string                 `json:"name"`
	ServerId     string                 `json:"serverId"`
	ProductModel string                 `json:"productModel"`
	DevSn        string                 `json:"devSn"`
	VariableMap  map[string]interface{} `json:"variableMap"`
	dto.UserInfo `search:"-"`
}

func (d *ForwardRuleEditReq) Generate(model *models.SysForwardRule) (modMap map[string]interface{}) {
	// 可编辑项
	if len(d.Name) > 0 {
		model.Name = d.Name
	}
	if len(d.ServerId) > 0 {
		model.ServerId = d.ServerId
	}
	model.ProductModel = d.ProductModel
	model.DevSn = d.DevSn
	model.VariableMap = utils.MapToBytes(d.VariableMap)
	now := dto.LocalTime(time.Now())
	model.UpdateTime = &now
	modMap = make(map[string]interface{})
	if len(model.ProductModel) == 0 {
		modMap["product_model"] = ""
	}
	if len(model.DevSn) == 0 {
		modMap["dev_sn"] = ""
	}
	return
}

type RuleDeleteReq struct {
	Id           string `json:"id" vd:"len($)>0"`
	dto.UserInfo `search:"-"`

	ServerId string
}
